<template>
  <div :class="playerAreaClasses">
    <div class="player-header">
      <div class="player-name">{{ player.name }}</div>
      <div v-if="player.isActive && !isPlayerFinished" class="active-indicator">
        出牌中
      </div>
      <!-- 自动显示完成徽章 -->
      <div
        v-if="isPlayerFinished"
        class="finished-badge"
        title="该玩家已出完牌"
      >
        <span class="finished-icon">✓</span>
        <span class="finished-text">完成</span>
      </div>
    </div>

    <div class="player-content">
      <!-- 当前出牌显示
      <div class="current-play">
        <div v-if="player.currentPlay.length === 0" class="no-play">
          <div class="play-placeholder">等待出牌...</div>
        </div>
        <div v-else class="played-cards">
          <PokerCard
            v-for="card in player.currentPlay"
            :key="card.id"
            :card="card"
            size="small"
          />
        </div>
      </div> -->

      <!-- 玩家历史出牌记录 -->
      <div class="player-history-section">
        <div class="history-label">历史出牌</div>
        <PlayerHistoryDisplay
          :player-id="player.id"
          :player-name="player.name"
          :history="history"
          :trump-card="trumpCard"
          :max-display="3"
          @show-full-history="showHistoryModal = true"
        />
      </div>

      <!-- 手牌数量显示 (仅对非当前玩家) -->
      <!-- <div v-if="!isCurrentUser" class="hand-info">
        <div class="card-count">剩余: {{ player.handCards.length }}张</div>
      </div> -->

      <!-- 出牌按钮 (仅对人类玩家且轮到他们时,且未出完牌) -->
      <div
        v-if="canPlay && showPlayButton && !isPlayerFinished"
        class="play-actions"
      >
        <button class="btn btn-primary btn-sm" @click="handlePlayCards">
          出牌
        </button>
        <!-- 根据canPassPlayer属性显示过牌按钮 -->
        <button
          v-if="canPassPlayer"
          class="btn btn-secondary btn-sm"
          @click="handlePass"
        >
          过牌
        </button>
        <!-- 如果不能过牌，显示提示 -->
        <div v-if="!canPassPlayer && canPlay" class="must-play-hint">
          必须出牌
        </div>
      </div>

      <!-- AI思考状态 -->
      <div v-if="isAIThinking" class="ai-thinking">
        <div class="thinking-indicator">
          <span class="thinking-dots">AI思考中</span>
        </div>
      </div>

      <!-- AI建议出牌显示 -->
      <div
        v-if="
          player.type === 'ai' &&
          (aiHasError ||
            aiShouldPass ||
            (aiSuggestedCards && aiSuggestedCards.length > 0))
        "
        class="ai-suggestion"
        :class="{ 'ai-suggestion--error': aiHasError }"
      >
        <!-- 错误提示 -->
        <div v-if="aiHasError" class="suggestion-label suggestion-label--error">
          ❌ 接口错误: {{ aiErrorMessage }}
        </div>

        <!-- 过牌提示 -->
        <div v-else-if="aiShouldPass" class="suggestion-label">
          AI建议：过牌
        </div>

        <!-- 出牌提示 -->
        <template v-else>
          <div class="suggestion-label">AI建议出牌：</div>
          <div class="suggested-cards">
            <PokerCard
              v-for="card in aiSuggestedCards"
              :key="card.id"
              :card="card"
              size="small"
              :selectable="false"
            />
          </div>
        </template>
      </div>
    </div>

    <!-- 出牌选择弹框 -->
    <CardSelector
      v-if="showCardSelector"
      :visible="showCardSelector"
      :selected-cards="selectedCards"
      :title="`${player.name} - 选择出牌`"
      :patternShow="player.type !== 'ai'"
      :played-cards="playedCards"
      multiple
      :skipValidation="player.type !== 'ai'"
      @confirm="handleCardsConfirm"
      @cancel="showCardSelector = false"
    />

    <!-- 完整历史记录弹窗 -->
    <PlayerHistoryModal
      :visible="showHistoryModal"
      :player-id="player.id"
      :player-name="player.name"
      :history="history"
      :trump-card="trumpCard"
      @close="showHistoryModal = false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { Player, PlayerType, GameHistory } from '../types/game'
import { Card } from '../types/card'
import PokerCard from './PokerCard.vue'
import CardSelector from './CardSelector.vue'
import PlayerHistoryDisplay from './PlayerHistoryDisplay.vue'
import PlayerHistoryModal from './PlayerHistoryModal.vue'

interface Props {
  player: Player
  isCurrentUser?: boolean
  canPlay?: boolean
  isAIThinking?: boolean
  showPlayButton?: boolean
  canPassPlayer?: boolean // 是否可以过牌
  history?: GameHistory[] // 游戏历史记录
  trumpCard?: Card | null // 级牌
  aiSuggestedCards?: Card[] // AI建议的牌
  aiShouldPass?: boolean // AI是否建议过牌
  aiHasError?: boolean // AI接口是否出错
  aiErrorMessage?: string // AI错误信息
}

interface Emits {
  (e: 'playCards', playerId: number, cards: Card[]): void
  (e: 'pass', playerId: number): void
  (e: 'markFinished', playerId: number): void
}

const props = withDefaults(defineProps<Props>(), {
  isCurrentUser: false,
  canPlay: false,
  isAIThinking: false,
  showPlayButton: true,
  canPassPlayer: true, // 默认可以过牌
  history: () => [], // 默认空数组
  aiSuggestedCards: () => [], // 默认空数组
  aiShouldPass: false, // 默认不过牌
  aiHasError: false, // 默认无错误
  aiErrorMessage: '', // 默认无错误信息
})

const emit = defineEmits<Emits>()

// 响应式数据
const showCardSelector = ref(false)
const selectedCards = ref<Card[]>([])
const showHistoryModal = ref(false)

// 计算属性
const playerAreaClasses = computed(() => [
  'player-area',
  `player-area--${props.player.position}`,
  {
    'player-area--active': props.player.isActive,
    'player-area--ai': props.player.type === PlayerType.AI,
    'player-area--current-user': props.isCurrentUser,
    'player-area--thinking': props.isAIThinking,
  },
])

// 获取本局已出过的所有牌
const playedCards = computed(() => {
  const cards: Card[] = []
  if (props.history && props.history.length > 0) {
    props.history.forEach((record) => {
      cards.push(...record.cards)
    })
  }
  return cards
})

// 计算当前玩家已出牌数量
const playerPlayedCardsCount = computed(() => {
  if (!props.history || props.history.length === 0) return 0

  let count = 0
  props.history.forEach((record) => {
    if (record.playerId === props.player.id) {
      count += record.cards.length
    }
  })
  return count
})

// 判断玩家是否已出完牌（已出牌数量 >= 27）
const isPlayerFinished = computed(() => {
  return playerPlayedCardsCount.value >= 27 || props.player.isFinished
})

// 方法
const handlePlayCards = () => {
  if (props.isCurrentUser) {
    // 当前用户从手牌中选择
    selectedCards.value = []
    showCardSelector.value = true
  } else {
    // 其他玩家手动录入
    selectedCards.value = []
    showCardSelector.value = true
  }
}

const handlePass = () => {
  emit('pass', props.player.id)
}

const handleCardsConfirm = (cards: Card[]) => {
  console.log('PlayerArea - handleCardsConfirm 被调用', {
    playerId: props.player.id,
    cardsCount: cards.length,
  })
  // 不立即关闭选择器，等待出牌结果
  if (cards.length > 0) {
    emit('playCards', props.player.id, cards)
  } else {
    // 如果没有选择牌，直接关闭
    showCardSelector.value = false
  }
}

// 暴露方法给父组件调用
defineExpose({
  closeCardSelector: () => {
    console.log('PlayerArea - closeCardSelector 被调用', {
      playerId: props.player.id,
      currentShowCardSelector: showCardSelector.value,
    })
    showCardSelector.value = false
  },
})
</script>

<style scoped>
.player-area {
  background: rgba(255, 255, 255, 0.1);
  border: 2px solid rgba(255, 255, 255, 0.2);
  border-radius: var(--border-radius-lg);
  padding: var(--spacing-md);
  min-height: 120px;
  transition: var(--transition);
  position: relative;
}

.player-area--active {
  border-color: var(--btn-primary);
  background: rgba(253, 126, 20, 0.1);
  box-shadow: 0 0 20px rgba(253, 126, 20, 0.3);
}

.player-area--ai {
  border-color: rgba(111, 66, 193, 0.5);
}

.player-area--current-user {
  border-color: rgba(40, 167, 69, 0.5);
}

.player-area--thinking {
  border-color: var(--joker-color);
  background: rgba(111, 66, 193, 0.1);
}

/* 玩家头部 */
.player-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-sm);
}

.player-name {
  color: white;
  font-weight: bold;
  font-size: 14px;
}

.finished-badge {
  display: flex;
  align-items: center;
  gap: 4px;
  background: linear-gradient(135deg, #f39c12, #e67e22);
  color: white;
  border-radius: 6px;
  padding: 4px 10px;
  font-size: 13px;
  font-weight: bold;
  box-shadow: 0 2px 8px rgba(243, 156, 18, 0.4);
  animation: finishedPulse 2s ease-in-out infinite;
}

.finished-icon {
  font-size: 14px;
  font-weight: bold;
  background: white;
  color: #f39c12;
  border-radius: 50%;
  width: 18px;
  height: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  line-height: 1;
}

.finished-text {
  letter-spacing: 1px;
}

@keyframes finishedPulse {
  0%,
  100% {
    transform: scale(1);
    box-shadow: 0 2px 8px rgba(243, 156, 18, 0.4);
  }
  50% {
    transform: scale(1.05);
    box-shadow: 0 4px 12px rgba(243, 156, 18, 0.6);
  }
}

.active-indicator {
  background: var(--btn-primary);
  color: white;
  padding: 2px 8px;
  border-radius: var(--border-radius-sm);
  font-size: 12px;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0.7;
  }
}

/* 玩家内容 */
.player-content {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-sm);
}

/* 当前出牌 */
.current-play {
  min-height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.no-play {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.play-placeholder {
  color: rgba(255, 255, 255, 0.6);
  font-style: italic;
  font-size: 12px;
}

.played-cards {
  display: flex;
  gap: var(--spacing-xs);
  flex-wrap: wrap;
  justify-content: center;
}

/* 手牌信息 */
.hand-info {
  text-align: center;
}

.card-count {
  color: rgba(255, 255, 255, 0.8);
  font-size: 12px;
}

/* 出牌操作 */
.play-actions {
  display: flex;
  flex-direction: row;
  gap: var(--spacing-sm);
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
}

.must-play-hint {
  color: #ff9800;
  font-size: 11px;
  font-weight: bold;
  padding: 2px 6px;
  background: rgba(255, 152, 0, 0.2);
  border-radius: 3px;
  border: 1px solid #ff9800;
}

/* 玩家历史记录区域 */
.player-history-section {
  margin-top: var(--spacing-xs);
  padding-top: var(--spacing-xs);
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.history-label {
  color: rgba(255, 255, 255, 0.6);
  font-size: 10px;
  margin-bottom: 4px;
  text-align: center;
}

.btn-sm {
  padding: 4px 12px;
  font-size: 12px;
}

/* AI思考状态 */
.ai-thinking {
  display: flex;
  justify-content: center;
  align-items: center;
}

.thinking-indicator {
  color: var(--joker-color);
  font-size: 12px;
  font-weight: bold;
}

.thinking-dots::after {
  content: '...';
  animation: thinking 1.5s infinite;
}

@keyframes thinking {
  0%,
  20% {
    content: '.';
  }
  40% {
    content: '..';
  }
  60%,
  100% {
    content: '...';
  }
}

/* AI建议出牌显示 */
.ai-suggestion {
  margin-top: var(--spacing-sm);
  padding: var(--spacing-sm);
  background: rgba(255, 255, 255, 0.95);
  border: 2px solid var(--btn-primary);
  border-radius: var(--border-radius-md);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.suggestion-label {
  color: #333;
  font-size: 14px;
  font-weight: bold;
  margin-bottom: var(--spacing-xs);
}

.suggested-cards {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
  justify-content: flex-start;
}

/* AI建议错误状态 */
.ai-suggestion--error {
  background: rgba(255, 82, 82, 0.95);
  border-color: #ff5252;
}

.suggestion-label--error {
  color: white;
  font-weight: bold;
}

/* 位置特定样式 */
.player-area--top {
  /* 上方玩家 */
}

.player-area--right {
  /* 右方玩家 */
}

.player-area--bottom {
  /* 下方玩家 (当前用户或AI) */
}

.player-area--left {
  /* 左方玩家 */
}

/* 响应式设计 */
@media (max-width: 768px) {
  .player-area {
    padding: var(--spacing-sm);
    min-height: 100px;
  }

  .player-name {
    font-size: 12px;
  }

  .active-indicator {
    font-size: 10px;
    padding: 1px 6px;
  }

  .played-cards {
    gap: 2px;
  }

  .play-actions {
    flex-direction: column;
    gap: 4px;
  }

  .btn-sm {
    padding: 3px 8px;
    font-size: 11px;
  }
}

/* 悬浮效果已删除 */
</style>
